import cv2
import numpy as np
from collections import deque
import gc

from memory_profiler import profile
class Node:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.parent = None

# @profile(precision=4)
def wavefront_detect(image_path):
    gc.disable()
    # 读取图像
    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

    # 检查图片是否正确加载
    if image is None:
        print("无法加载图片")
        return None

    # 创建一个彩色图像以便显示红色边界
    color_image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
    # white_pixels = np.where((color_image == [255, 255, 255]).all(axis=2))
    # # 如果有白色像素，获取第一个白色像素的坐标
    # if len(white_pixels[0]) > 0:
    #     white_pixel_position = (white_pixels[0][0], white_pixels[1][0])
    #     print("找到一个白色区域的位置:", white_pixel_position)
    # else:
    #     print("没有找到白色区域")

    # 定义灰色和白色的阈值
    # gray_value = 128
    gray_value_low = 100
    gray_value_top = 240
    # white_value = 255
    white_value_low = 249
    white_value_top = 255

    # 初始化边界检测
    height, width = image.shape
    visited = np.zeros((height, width), dtype=bool)
    queue = deque()
    frontier_list = []
    print(visited.shape)

    # 从中心开始
    # start_x, start_y = width // 2, height // 2
    # start_x, start_y = white_pixel_position
    # start_x, start_y = 600, 520
    # start_x, start_y = 220, 95
    start_x, start_y = 2000, 4000
    queue.append((start_x, start_y))
    visited[start_y, start_x] = True

    # 方向向量
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]

    while queue:
        x, y = queue.popleft()
        # print("我还在运行")
        # print(len(queue))
        for dx, dy in directions:
            nx, ny = x + dx, y + dy
            if 0 <= nx < width and 0 <= ny < height:
                if white_value_low <= image[ny, nx] <= white_value_top and not visited[ny, nx]:
                    queue.append((nx, ny))
                    visited[ny, nx] = True
                    # print(ny, nx)
                    # print(image[ny][nx])
                    # for ddx, ddy in directions:
                    #     print(image[ny + ddy, nx + ddx])
                    # 检查是否是边界
                    if  any(gray_value_low <= image[ny + ddy, nx + ddx] <= gray_value_top for ddx, ddy in directions if
                                             0 <= nx + ddx < width and 0 <= ny + ddy < height):
                    # if 0 <= any(image[ny + ddy, nx + ddx] for ddx, ddy in directions if
                    #                          0 <= nx + ddx < width and 0 <= ny + ddy < height) <= 255:

                        color_image[ny, nx] = [0, 0, 255]  # 标记为红色
                        frontier_list.append(Node(nx,ny))
                        # print("是红色")
                # elif white_value_low <= image[ny, nx] <= white_value_top:
                #     queue.append((nx, ny))

    # 显示结果
    # cv2.imshow('waveFront frontier Detection', color_image)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    return len(frontier_list)


if __name__ == '__main__':
    # 使用该函数
    wavefront_detect('path_to_your_image.jpg')
